package com.xiang.utils;

import com.xiang.config.EsConfig;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 过滤查询
 *
 * @author xiangtianlei@gogpay.cn
 * @date 2023-01-30
 */
public class FilterQuery {
    RestHighLevelClient client = EsConfig.getClient();
    Logger logger = LoggerFactory.getLogger(CreateDoc.class);

    /**
     * 过滤查询
     */
    @Test
    public void filterQuery() throws IOException {
        SearchRequest request = new SearchRequest(EsConfig.INDEX_NAME);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //  构造filter查询
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.filter(QueryBuilders.termQuery("address", "云南"));
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("age").lte(30));
        // 封装到query中
        builder.query(boolQueryBuilder);
        request.source(builder);
        // 请求
        SearchResponse res = client.search(request, RequestOptions.DEFAULT);
        logger.info("查询DSL语句：{}", request.source().toString());
        logger.info("查询出的数据：{}条", res.getHits().getHits().length);
        logger.info("总数：{}", res.getHits().getTotalHits());
    }
}
